<template>
  <div class="addAddress absolute">
    <div class="list">
      <div class="item acea-row row-between-wrapper">
        <div class="name">收货人姓名</div>
        <input
          type="text"
          @input="widthCheck($event.target,100)"
          placeholder="请填写收货人姓名"
          v-model="userAddress.real_name"
          required
        />
      </div>
      <div class="item acea-row row-between-wrapper">
        <div class="name">收货人手机</div>
        <input
          type="tel"
          maxlength="11"
          placeholder="请填写联系电话"
          v-model="userAddress.phone"
          required
        />
      </div>
      <div class="item acea-row row-between-wrapper">
        <div class="name">收货人所在地区</div>
        <div
          class="picker acea-row row-between-wrapper select-value form-control"
        >
          <div class="address">
            <div slot="right" @click.stop="show2 = true">
              {{ model2 || "城市选择" }}
            </div>
            <CitySelect
              ref="cityselect"
              v-model="show2"
              :callback="result2"
              :items="district"
              :ready="ready"
              provance=""
              city=""
              area=""
            ></CitySelect>
          </div>
          <div class="iconfont font-color-red"></div>
        </div>
      </div>
      <div class="item acea-row row-between-wrapper" style="display: flex;align-items: baseline;">
        <div class="name">收货人地址</div>
        <!-- <input
          type="text"
          placeholder="街道，门牌号等"
          v-model="userAddress.detail"
          required
        /> -->
        <textarea
          placeholder="街道，门牌号等"
          @blur="onBlurInput()"
          @input="widthCheck($event.target,100)"
          v-model="userAddress.detail"
          required
        ></textarea>
      </div>
    </div>
    <!-- <div class="default acea-row row-middle">
      <div class="select-btn">
        <div class="checkbox-wrapper">
          <label class="well-check"
            ><input
              type="checkbox"
              name=""
              value=""
              @click="ChangeIsDefault"
              :checked="userAddress.is_default ? true : false"
            /><i class="icon"></i><span class="def">设置为默认地址</span></label
          >
        </div>
      </div>
    </div> -->
    <div></div>
    <div v-show="id" class="keepBnt" @click="submit()">完成</div>
    <div v-show="!id" class="keepBnt" @click="confirm()">完成</div>
    <!-- <div class="wechatAddress" v-if="isWechat && !id" @click="getAddress">
      导入微信地址
    </div> -->
    <!-- 二次确认弹窗 -->
    <div class="confirmBox" v-show="isConfirm == '1'">
      <div class="ceng">
        <p class="confirmTltle">是否更新您填写的地址？</p>
        <div>
          <span class="NoConfirm" @click="NoConfirm()">暂不更新</span>
          <span class="confirm" @click="confirm()">确定更新</span>
        </div>
      </div>
    </div>
    <!-- <noData></noData> -->
    <!-- 二次确认弹窗end -->
  </div>
</template>
<script type="text/babel">
import { CitySelect } from "vue-ydui/dist/lib.rem/cityselect";
import { getAddress, postAddress,postAddress1 } from "@api/user";
import { getCity } from "@api/public";
import attrs, { required, chs_phone } from "@utils/validate";
import { validatorDefaultCatch } from "@utils/dialog";
import { openAddress } from "@libs/wechat";
import { isWeixin } from "@utils";
import noData from "@components/noData";

export default {
  components: {
    CitySelect,
    noData
  },
  data() {
    return {
      show2: false,
      model2: "",
      district: [],
      id: 0,
      userAddress: { 
        is_default: 1 ,
        real_name:'',
        detail:'',
        },
      address: {},
      isWechat: isWeixin(),
      ready: false,
      //二次确认
      isConfirm: "0",
      is_defaultType:'1',
    };
  },
  mounted: function() {
    let id = this.$route.params.id;
    this.id = id;
    document.title = !id ? "添加地址" : "修改地址";
    if(this.$route.query.type == '-2'){
      // this.userAddress.real_name = this.$route.query.name;
      // this.userAddress.phone = this.$route.query.phone;
      // var addressList = this.$route.query.address.split(' ');
      // this.model2 = addressList[0]+' '+addressList[1]+' '+addressList[2];
      // this.address= {
      //       province: addressList[0],
      //       city: addressList[1],
      //       district: addressList[2]
      //     },
      this.is_defaultType = '0'
      // this.userAddress.detail = this.$route.query.address.split(this.model2)[1];
    }
    this.getUserAddress();
    this.getCityList();
  },
  methods: {
      onBlurInput () {
				window.scroll(0, 0)
			},
     //限制50个字符
         widthCheck (str, len) {
            var temp = 0
            for (var i = 0; i < str.value.length; i++) {
                if (/[\u4e00-\u9fa5]/.test(str.value[i])) {
                  temp += 2
                } else {
                  temp++
                }
                if (temp > len) {
                  str.value = str.value.substr(0, i)
                }
            }
        },
    NoConfirm() {
      this.isConfirm = "0";
      this.$router.go(-1);
    },
    async confirm() {
      let name = this.userAddress.real_name,
        phone = this.userAddress.phone,
        model2 = this.model2,
        detail = this.userAddress.detail,
        isDefault = 1;
      // try {
      //   await this.$validator({
      //     name: [
      //       required(required.message("姓名")),
      //       attrs.range([2, 50], attrs.range.message("姓名"))
      //     ],
      //     phone: [
      //       required(required.message("联系电话")),
      //       chs_phone(chs_phone.message())
      //     ],
      //     model2: [required("请选择地址")],
      //     detail: [required(required.message("具体地址")),attrs.range([2, 50], attrs.range.message("具体地址"))]
      //   }).validate({ name, phone, model2, detail });
      // } catch (e) {
      //   return validatorDefaultCatch(e);
      // }
       if (!this.id && this.$route.query.type != '-2') {
        try {
          let that = this,
            data = {
              id: that.id,
              real_name: name,
              phone: phone,
              address: this.address,
              detail: detail,
              is_default: this.is_defaultType,
              post_code: ""
            };
          postAddress(data)
            .then(function() {
              that.isConfirm = "0";
              if (that.id) that.$dialog.toast({ mes: "修改成功" });
              else that.$dialog.toast({ mes: "添加成功" });
              that.$router.go(-1);
            })
            .catch(err => {
              that.$dialog.error(err.msg);
            });
        } catch (e) {
          this.$dialog.error(e.msg);
        }
      } else if (this.$route.query.type == '-2') {
        try {
          let that = this,
            data = {
              id: '',
              order:that.id,
              real_name: name,
              phone: phone,
              address: this.address,
              detail: detail,
              is_default: this.is_defaultType,
              post_code: ""
            };
          postAddress1(data)
            .then(function() {
              that.isConfirm = "0";
              that.$dialog.toast({ mes: "修改成功" });
              that.$router.go(-1);
            })
            .catch(err => {
              that.$dialog.error(err.msg);
            });
        } catch (e) {
          this.$dialog.error(e.msg);
        }
      }else {
      
    
      try {
        let that = this,
          data = {
            id: that.id,
            real_name: name,
            phone: phone,
            address: this.address,
            detail: detail,
            is_default: 1,
            post_code: ""
          };
        postAddress(data)
          .then(function() {
            that.isConfirm = "0";
            if (that.id) that.$dialog.toast({ mes: "修改成功" });
            else that.$dialog.toast({ mes: "添加成功" });
             that.$router.go(-1);
          })
          .catch(err => {
            that.$dialog.error(err.msg);
          });
      } catch (e) {
        this.$dialog.error(e.msg);
      }
      }
    },
    getCityList: function() {
      let that = this;
      getCity()
        .then(res => {
          that.district = res.data;
          that.ready = true;
        })
        .catch(err => {
          that.$dialog.error(err.msg);
        });
    },
    getUserAddress: function() {
      if (!this.id) return false;
      if (this.$route.query.type == '-2') return false;
      let that = this;
      getAddress(that.id)
        .then(res => {
          console.log(res);
          that.userAddress = res.data;
          that.model2 =
            res.data.province + " " + res.data.city + " " + res.data.district;
          that.address.province = res.data.province;
          that.address.city = res.data.city;
          that.address.city_id = res.data.city_id;
          that.address.district = res.data.district;
        })
        .catch(err => {
          that.$dialog.error(err.msg);
        });
    },
    getAddress() {
      openAddress().then(userInfo => {
        this.$dialog.loading.open();
        postAddress({
          id: this.id,
          real_name: userInfo.userName,
          phone: userInfo.telNumber,
          address: {
            province: userInfo.provinceName,
            city: userInfo.cityName,
            district: userInfo.countryName
          },
          detail: userInfo.detailInfo,
          is_default: 1,
          post_code: userInfo.postalCode,
          type: 1
        })
          .then(() => {
            this.$dialog.loading.close();
            this.$dialog.toast({ mes: "添加成功" });
            this.$router.go(-1);
          })
          .catch(err => {
            this.$dialog.loading.close();
            this.$dialog.error(err.msg || "添加失败");
          });
      });
    },
    async submit() {
      let name = this.userAddress.real_name.trim(),
        phone = this.userAddress.phone,
        model2 = this.model2,
        detail = this.userAddress.detail.trim(),
        isDefault = 1;

      try {
        await this.$validator({
          name: [
            required(required.message("姓名")),
            attrs.range([2, 50], attrs.range.message("姓名"))
          ],
          phone: [
            required(required.message("联系电话")),
            chs_phone(chs_phone.message())
          ],
          model2: [required("请选择地址")],
          detail: [required(required.message("具体地址")),attrs.range([2, 50], attrs.range.message("具体地址"))]
        }).validate({ name, phone, model2, detail });
      } catch (e) {
        return validatorDefaultCatch(e);
      }
     
        this.isConfirm = "1";
      
    },
    // ChangeIsDefault: function() {
    //   this.userAddress.is_default = !this.userAddress.is_default;
    // },
    result2(ret) {
      this.model2 = ret.itemName1 + " " + ret.itemName2 + " " + ret.itemName3;
      this.address.province = ret.itemName1;
      this.address.city = ret.itemName2;
      this.address.district = ret.itemName3;
      this.address.city_id = ret.itemValue2;
    }
  }
};
</script>
<style scoped lang="scss">
.name{
  color: rgba(0,0,0,.7);
  font-weight: 400;
  font-size: 0.28rem;
}
.confirmBox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: rgba(0, 0, 0, 0.3);
  overflow: hidden;
  .ceng {
    display: block;
    width: 6rem;
    height: 2.9rem;
    background: rgba(255, 255, 255, 1);
    border-radius: 0.16rem;
    justify-content: center;
    margin: 50% auto 0;
    justify-items: center;
    .confirmTltle {
      width: 100%;
      height: 1.84rem;
      line-height: 1.84rem;
      text-align: center;
      font-size: 0.34rem;
      color: #333;
      border-bottom: 1px solid rgba(0, 0, 0, 0.2);
    }
    .NoConfirm {
      display: inline-block;
      width: 50%;
      height: 1.04rem;
      line-height: 1.04rem;
      text-align: center;
      font-size: 0.32rem;
      color: rgba(0, 0, 0, 0.5);
      border-right: 1px solid rgba(0, 0, 0, 0.2);
    }
    .confirm {
      display: inline-block;
      width: 50%;
      height: 1.04rem;
      line-height: 1.04rem;
      text-align: center;
      font-size: 0.32rem;
      color: rgba(68, 115, 225, 1);
    }
  }
}
</style>
